package com.mapfinal.server.geoserver;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import com.jfinal.kit.StrKit;
import com.lambkit.Lambkit;
import com.lambkit.core.aop.AopKit;
import com.lambkit.core.config.ConfigManager;

public class GeoserverManager {

	private static final String DATASOURCE_PREFIX = "mapfinal.geoserver.";
	private static GeoserverManager manager;

	public static GeoserverManager me() {
		if (manager == null) {
			manager = AopKit.singleton(GeoserverManager.class);
		}
		return manager;
	}

	//private GeoserverService service;
	private GeoserverClusterServer servers;

	private GeoserverManager() {
		//service = new GeoserverService();

		GeoserverConfig geoserverConfig = Lambkit.config(GeoserverConfig.class, "mapfinal.geoserver");
		geoserverConfig.setName(GeoserverConfig.NAME_DEFAULT);
		servers.addServer(GeoserverServer.create(geoserverConfig));

		Properties prop = ConfigManager.me().getProperties();
		Set<String> geoserverNames = new HashSet<>();
		for (Map.Entry<Object, Object> entry : prop.entrySet()) {
			String key = entry.getKey().toString();
			if (key.startsWith(DATASOURCE_PREFIX) && entry.getValue() != null) {
				String[] keySplits = key.split("\\.");
				if (keySplits.length == 4) {
					geoserverNames.add(keySplits[2]);
				}
			}
		}

		for (String name : geoserverNames) {
			GeoserverConfig dsc = ConfigManager.me().get(GeoserverConfig.class, DATASOURCE_PREFIX + name);
			if (StrKit.isBlank(dsc.getName())) {
				dsc.setName(name);
			}
			servers.addServer(GeoserverServer.create(dsc));
		}
	}
	
	public List<GeoserverServer> getServers(String layerName) {
		return servers.getServers(layerName);
	}

	public GeoserverServer getBestServer(String layerName) {
		return servers.getBestServer(layerName);
	}
	
	public GeoserverServer getServer(String name) {
		return servers.getServer(name);
	}

	public GeoserverServer getDefaultServer() {
		return servers.getDefaultServer();
	}
/*
	public GeoserverService getService() {
		return service;
	}

	public void setService(GeoserverService service) {
		this.service = service;
	}
*/
}
